package com.ayi.dao.cartdao;

import com.ayi.bean.Book;
import com.ayi.bean.User;
import com.ayi.utils.CloseConn;
import com.ayi.utils.GetConn;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import static com.ayi.constants.BookShopConstants.ConstantMethods.executeSqlUpdateCartList;

/**
 * @author Ayingzz
 * @create 2021/11/29 22:23
 */
public class DeleteCart {

    /**
     * 把一本书移除出购物车
     * @param username
     * @param book
     * @return
     */
    public boolean deletedBookFromCartByUsername(String username, Book book) {
        Connection conn = new GetConn().getConnection();
        StringBuilder sb = new QueryCart().queryCartWithCreateAStringBuilderByUsername(username);
        int startIndex = sb.indexOf(book.getId() + "=");
        if (startIndex != -1) {
            int endIndex = startIndex;
            for (int i = startIndex, n = sb.length(); i < n; i++) {
                if (sb.charAt(i) == '#') {
                    endIndex = i + 1;
                    break;
                }
            }
            sb.delete(startIndex, endIndex);
        }
        String sql = "update Carts set cartList = ? where username = ?";
        return executeSqlUpdateCartList(username, conn, sb, sql);
    }

}
